/*
 * Copyright (C) 2022 KylinSoft Co., Ltd.
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */

#include "icontheme.h"

#include <KIconTheme>
#include <QGSettings>
#include <QIcon>

#include <QDebug>

namespace UKUI {

static IconTheme* g_icon_theme;

IconTheme::IconTheme()
{
    initConnect();
}

IconTheme* IconTheme::getInstance()
{
    if (!g_icon_theme)
        g_icon_theme = new IconTheme();
    return g_icon_theme;
}

QString IconTheme::getPathFromName(QString iconName, uint iconSize)
{
    QGSettings iconStyle("org.ukui.style");
    QString iconThemeName;

    if (iconStyle.keys().contains("iconThemeName")) {
        iconThemeName = iconStyle.get("iconThemeName").toString();
    }
    KIconTheme iconInfo(iconThemeName);
    return iconInfo.iconPathByName(iconName, iconSize, KIconLoader::MatchBest);
}

QString IconTheme::iconTheme() const
{
    QGSettings iconStyle("org.ukui.style");
    if (!iconStyle.keys().contains("iconThemeName")) {
        return QString();
    }
    return iconStyle.get("iconThemeName").toString();
}

void IconTheme::initConnect()
{
    if (!QGSettings::isSchemaInstalled("org.ukui.style")) {
        qWarning() << __FUNCTION__ << __FILE__ << "can not find schema org.ukui.style";
        return;
    }
    QGSettings* iconThemeSettings = new QGSettings("org.ukui.style", "/org/ukui/style/");
    connect(iconThemeSettings, &QGSettings::changed, [&](const QString& value) {
        if (value == "iconThemeName") {
            emit iconThemeChanged();
        }
    });
}

} // namespace UKUI
